package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.banshengyanyu.bottomtrackviewlib.TrackModel;
import com.banshengyanyu.bottomtrackviewlib.interfaces.ClipVideoListener;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;
import com.stark.ve.core.SpeedMode;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.adapter.VideoFilterAdapter;
import flc.ast.adapter.VideoMusicAdapter;
import flc.ast.adapter.VideoStickerAdapter;
import flc.ast.bean.MusicBean;
import flc.ast.bean.MyColorBean;
import flc.ast.bean.MyStickerBean;
import flc.ast.bean.MyVideoFilterBean;
import flc.ast.databinding.ActivityVideoEditBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.ProgressConvertUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkLinearLayout;
import stark.common.basic.view.container.StkRelativeLayout;

public class VideoEditActivity extends BaseAc<ActivityVideoEditBinding> implements ClipVideoListener {

    public static String videoPath = "";
    private String oldPath = "";//初始路径
    private String savePath = "";//保存路径
    private long videoLength;
    private long tailorStartTime;//剪切开始时间
    private long tailorEndTime;//剪切结束时间
    private VideoFilterAdapter filterAdapter;
    private VideoMusicAdapter musicAdapter;
    private int filterPos = 0, musicPos = 0, stickerPos = 0, colorPos = 0;
    private boolean isFilter = false;
    private String filter = "";
    private String musicPath = "";
    private boolean mClickClose = true;//关闭原声
    private float voiceCount = 0.0f;
    private float mCurSpeed = 1.0f;
    private float minSpeed;//最小速度
    private float maxSpeed;//最大速度
    private VideoStickerAdapter stickerAdapter;
    private int videoWidth, videoHeight;
    private ColorAdapter colorAdapter;
    private Dialog mySaveDialog;
    private SeekBar seekBar;
    private TextView textView;
    private StkLinearLayout llVideoSaveSuc;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_edit;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivVideoEditBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //滤镜
        mDataBinding.rvVideoFilterList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        filterAdapter = new VideoFilterAdapter();
        mDataBinding.rvVideoFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
        //音乐
        mDataBinding.rvVideoMusicList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        musicAdapter = new VideoMusicAdapter();
        mDataBinding.rvVideoMusicList.setAdapter(musicAdapter);
        musicAdapter.setOnItemClickListener(this);
        //变速
        minSpeed = EditorHolder.editor().supportMinSpeed();
        maxSpeed = EditorHolder.editor().supportMaxSpeed();
        mDataBinding.sbSpeed.setMax(100);
        mDataBinding.sbSpeed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mCurSpeed = ProgressConvertUtil.progress2value(progress, minSpeed, maxSpeed, 100);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        int curProgress = ProgressConvertUtil.value2Progress(mCurSpeed, minSpeed, maxSpeed, 100);
        mDataBinding.sbSpeed.setProgress(curProgress);
        //贴纸
        mDataBinding.rvVideoStickerList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        stickerAdapter = new VideoStickerAdapter();
        mDataBinding.rvVideoStickerList.setAdapter(stickerAdapter);
        stickerAdapter.setOnItemClickListener(this);
        //文字
        mDataBinding.rvVideoTextColorList.setLayoutManager(new GridLayoutManager(mContext, 8));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvVideoTextColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);

        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivPlayFull.setOnClickListener(this);
        mDataBinding.ivVideoEditSave.setOnClickListener(this);
        mDataBinding.ivVideoCut.setOnClickListener(this);
        mDataBinding.ivCutCancel.setOnClickListener(this);
        mDataBinding.ivCutConfirm.setOnClickListener(this);
        mDataBinding.ivVideoFilter.setOnClickListener(this);
        mDataBinding.ivFilterCancel.setOnClickListener(this);
        mDataBinding.ivFilterConfirm.setOnClickListener(this);
        mDataBinding.ivVideoMusic.setOnClickListener(this);
        mDataBinding.ivMusicConfirm.setOnClickListener(this);
        mDataBinding.ivMusicCancel.setOnClickListener(this);
        mDataBinding.llMusicClose.setOnClickListener(this);
        mDataBinding.ivVideoSpeed.setOnClickListener(this);
        mDataBinding.ivSpeedCancel.setOnClickListener(this);
        mDataBinding.ivSpeedConfirm.setOnClickListener(this);
        mDataBinding.llSpeed1.setOnClickListener(this);
        mDataBinding.llSpeed2.setOnClickListener(this);
        mDataBinding.llSpeed3.setOnClickListener(this);
        mDataBinding.llSpeed4.setOnClickListener(this);
        mDataBinding.ivVideoSticker.setOnClickListener(this);
        mDataBinding.ivStickerCancel.setOnClickListener(this);
        mDataBinding.ivStickerConfirm.setOnClickListener(this);
        mDataBinding.ivVideoText.setOnClickListener(this);
        mDataBinding.ivTextConfirm.setOnClickListener(this);
        mDataBinding.ivTextCancel.setOnClickListener(this);
        mDataBinding.ivTextAdd.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart://播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azantinzhong2);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivVideoEditSave://保存
                saveVideo();
                break;
            case R.id.ivVideoCut://剪辑
                mDataBinding.llVideoEditBottom.setVisibility(View.GONE);
                mDataBinding.llVideoCut.setVisibility(View.VISIBLE);
                break;
            case R.id.ivCutConfirm:
                cutVideo();
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoCut.setVisibility(View.GONE);
                break;
            case R.id.ivCutCancel:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoCut.setVisibility(View.GONE);
                break;
            case R.id.ivVideoFilter://滤镜
                mDataBinding.llVideoEditBottom.setVisibility(View.GONE);
                mDataBinding.llVideoFilter.setVisibility(View.VISIBLE);
                break;
            case R.id.ivFilterConfirm:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoFilter.setVisibility(View.GONE);
                savePath = videoPath;
                oldPath = videoPath;
                //设置播放器
//                mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                mDataBinding.videoView.setVideoPath(videoPath);
//                mDataBinding.videoView.seekTo(1);
//                mDataBinding.videoView.start();
                startTime();
                break;
            case R.id.ivFilterCancel:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoFilter.setVisibility(View.GONE);
                videoPath = oldPath;
                //设置播放器
//                mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                mDataBinding.videoView.setVideoPath(videoPath);
//                mDataBinding.videoView.seekTo(1);
//                mDataBinding.videoView.start();
                startTime();
                break;
            case R.id.ivVideoMusic://音乐
                mDataBinding.llVideoEditBottom.setVisibility(View.GONE);
                mDataBinding.llVideoMusic.setVisibility(View.VISIBLE);
                break;
            case R.id.llMusicClose:
                if (mClickClose) {
                    mClickClose = false;
                    mDataBinding.ivMusicClose.setSelected(true);
                } else {
                    mClickClose = true;
                    mDataBinding.ivMusicClose.setSelected(false);
                }
                break;
            case R.id.ivMusicConfirm:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoMusic.setVisibility(View.GONE);
                savePath = videoPath;
                oldPath = videoPath;
                mDataBinding.videoView.setVideoPath(videoPath);
                startTime();
                break;
            case R.id.ivMusicCancel:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoMusic.setVisibility(View.GONE);
                videoPath = oldPath;
                mDataBinding.videoView.setVideoPath(videoPath);
                startTime();
                break;
            case R.id.ivVideoSpeed://变速
                mDataBinding.llVideoEditBottom.setVisibility(View.GONE);
                mDataBinding.llVideoSpeed.setVisibility(View.VISIBLE);
                break;
            case R.id.ivSpeedConfirm:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoSpeed.setVisibility(View.GONE);
                videoSpeed();
                break;
            case R.id.ivSpeedCancel:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoSpeed.setVisibility(View.GONE);
                //设置播放器
                mDataBinding.videoView.setVideoPath(videoPath);
                startTime();
                break;
            case R.id.llSpeed1://0.5
                clearSelection();
                mDataBinding.llSpeed1.setBackgroundColor(Color.parseColor("#32DCA3"));
                mDataBinding.tvSpeed1.setTextColor(Color.parseColor("#FFFFFF"));
                mCurSpeed = 0.5f;
                int curProgress = ProgressConvertUtil.value2Progress(mCurSpeed, minSpeed, maxSpeed, 100);
                mDataBinding.sbSpeed.setProgress(curProgress);
                break;
            case R.id.llSpeed2://1.0
                clearSelection();
                mDataBinding.llSpeed2.setBackgroundColor(Color.parseColor("#32DCA3"));
                mDataBinding.tvSpeed2.setTextColor(Color.parseColor("#FFFFFF"));
                mCurSpeed = 1.0f;
                int curProgress2 = ProgressConvertUtil.value2Progress(mCurSpeed, minSpeed, maxSpeed, 100);
                mDataBinding.sbSpeed.setProgress(curProgress2);
                break;
            case R.id.llSpeed3://1.5
                clearSelection();
                mDataBinding.llSpeed3.setBackgroundColor(Color.parseColor("#32DCA3"));
                mDataBinding.tvSpeed3.setTextColor(Color.parseColor("#FFFFFF"));
                mCurSpeed = 1.5f;
                int curProgress3 = ProgressConvertUtil.value2Progress(mCurSpeed, minSpeed, maxSpeed, 100);
                mDataBinding.sbSpeed.setProgress(curProgress3);
                break;
            case R.id.llSpeed4://2.0
                clearSelection();
                mDataBinding.llSpeed4.setBackgroundColor(Color.parseColor("#32DCA3"));
                mDataBinding.tvSpeed4.setTextColor(Color.parseColor("#FFFFFF"));
                mCurSpeed = 2.0f;
                int curProgress4 = ProgressConvertUtil.value2Progress(mCurSpeed, minSpeed, maxSpeed, 100);
                mDataBinding.sbSpeed.setProgress(curProgress4);
                break;
            case R.id.ivVideoSticker://贴纸
                mDataBinding.llVideoEditBottom.setVisibility(View.GONE);
                mDataBinding.llVideoSticker.setVisibility(View.VISIBLE);
                break;
            case R.id.ivStickerConfirm:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoSticker.setVisibility(View.GONE);
                mDataBinding.ivStickerView.setShowHelpToolFlag(false);
                videoSticker();
                break;
            case R.id.ivStickerCancel:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoSticker.setVisibility(View.GONE);
                //设置播放器
                mDataBinding.videoView.setVideoPath(videoPath);
                startTime();
                break;
            case R.id.ivVideoText://文字
                mDataBinding.llVideoEditBottom.setVisibility(View.GONE);
                mDataBinding.llVideoText.setVisibility(View.VISIBLE);
                break;
            case R.id.ivTextConfirm:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoText.setVisibility(View.GONE);
                mDataBinding.txtStickerView.setShowHelpBox(false);
                videoText();
                break;
            case R.id.ivTextCancel:
                mDataBinding.llVideoEditBottom.setVisibility(View.VISIBLE);
                mDataBinding.llVideoText.setVisibility(View.GONE);
                //设置播放器
                mDataBinding.videoView.setVideoPath(videoPath);
                startTime();
                break;
            case R.id.ivTextAdd://添加文字
                KeyboardUtils.hideSoftInput(this);
                if (TextUtils.isEmpty(mDataBinding.etTextContent.getText().toString())) {
                    ToastUtils.showShort(R.string.please_input_text);
                    return;
                }
                mDataBinding.txtStickerView.setText(mDataBinding.etTextContent.getText().toString());
                break;
            case R.id.tvGoRecord://前往查看
                mySaveDialog.dismiss();
                startActivity(VideoRecordActivity.class);
                break;
            case R.id.ivPlayFull://放大
//                PlayActivity.videoUri = videoPath;
//                startActivity(PlayActivity.class);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == filterAdapter) {
            filterAdapter.getItem(filterPos).setSelect(false);
            filterAdapter.notifyItemChanged(filterPos);
            filterPos = position;
            filterAdapter.getItem(position).setSelect(true);
            filterAdapter.notifyItemChanged(position);
            //设置滤镜
            if (isFilter) return;
            filter = filterAdapter.getItem(position).getFilter();
            isFilter = true;
            //重置路径 --避免叠加
            videoPath = oldPath;
            filterVideo();
        } else if (adapter == musicAdapter) {
            musicAdapter.getItem(musicPos).setSelected(false);
            musicAdapter.getItem(position).setSelected(true);
            musicPos = position;
            musicAdapter.notifyDataSetChanged();

            if (mDataBinding.videoView.isPlaying()) {
                mDataBinding.videoView.pause();
            }
            showDialog(getString(R.string.video_music_loading) + 0 + "%");
            String music = saveToSDCard(musicAdapter.getItem(position).getMusicUrl());  // 将raw文件下的音乐下载到本地指定目录
            musicPath = FileUtil.generateFilePath(Content.Temp, ".mp4");
            //参数分别是视频路径，音频路径，输出路径,原始视频音量(1为100%,0.7为70%,以此类推),添加音频音量
            if (mClickClose) {
                voiceCount = 1.0f;
            } else {
                voiceCount = 0.0f;
            }
            EpEditor.music(videoPath, music, musicPath, voiceCount, 1.5f, new OnEditorListener() {
                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissDialog();
                            FileUtils.delete(music);  // 将下载的音乐文件删掉，防止下载了太多的音乐文件
                            videoPath = musicPath;
                            //设置播放器
                            mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                            mDataBinding.videoView.setVideoPath(videoPath);
                            mDataBinding.videoView.seekTo(1);
                            mDataBinding.videoView.start();
                            startTime();
                        }
                    });
                }

                @Override
                public void onFailure() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissDialog();
                            ToastUtils.showShort(R.string.video_music_fail);
                        }
                    });
                }

                @Override
                public void onProgress(float progress) {
                    showDialog(getString(R.string.video_music_loading) + Math.round(progress * 100) + "%");
                }
            });
        } else if (adapter == stickerAdapter) {
            stickerAdapter.getItem(stickerPos).setSelect(false);
            stickerAdapter.notifyItemChanged(stickerPos);
            stickerPos = position;
            stickerAdapter.getItem(position).setSelect(true);
            stickerAdapter.notifyItemChanged(position);
            //设置贴纸
            Resources res = getResources();
            Bitmap bmp = BitmapFactory.decodeResource(res, stickerAdapter.getItem(position).getImg());
            mDataBinding.ivStickerView.addBitImage(bmp);
        } else if (adapter == colorAdapter) {
            colorAdapter.getItem(colorPos).setSelect(false);
            colorAdapter.notifyItemChanged(colorPos);
            colorPos = position;
            colorAdapter.getItem(position).setSelect(true);
            colorAdapter.notifyItemChanged(position);
            mDataBinding.txtStickerView.setTextColor(Color.parseColor(colorAdapter.getItem(position).getColor()));
        }
    }

    @Override
    protected void initData() {
        videoLength = MediaUtil.getDuration(videoPath);
        setPlayer();
        oldPath = videoPath;
        savePath = videoPath;
        //设置剪切功能
        mDataBinding.bottomTrackView.setClipVideoMode(TrackModel.ClipVideoMode.OPERATION);
        mDataBinding.bottomTrackView.setMode(TrackModel.ClipMode.CLIP);
        mDataBinding.bottomTrackView.initInfo(videoPath, videoLength, true,
                0, videoLength, 1.0f);
        mDataBinding.bottomTrackView.setClipVideoListener(this);
        //滤镜
        List<MyVideoFilterBean> listFilter = new ArrayList<>();
        listFilter.add(new MyVideoFilterBean("", getString(R.string.filter_text1), "#00000000", true));
        listFilter.add(new MyVideoFilterBean("lutyuv='u=128:v=128'", getString(R.string.filter_text2), "#323333", false));
        listFilter.add(new MyVideoFilterBean("hue='h=60:s=-3'", getString(R.string.filter_text3), "#C376F3", false));
        listFilter.add(new MyVideoFilterBean("lutyuv='y=maxval+minval-val:u=maxval+minval-val:v=maxval+minval-val'", getString(R.string.filter_text4), "#6F7171", false));
        listFilter.add(new MyVideoFilterBean("lutyuv=y=negval", getString(R.string.filter_text5), "#505151", false));
        listFilter.add(new MyVideoFilterBean("lutyuv='u=128:v=128'", getString(R.string.filter_text7), "#999999", false));
        listFilter.add(new MyVideoFilterBean("lutyuv='y=2*val'", getString(R.string.filter_text8), "#513232", false));
        listFilter.add(new MyVideoFilterBean("unsharp", getString(R.string.filter_text9), "#787A7A", false));
        filterAdapter.setList(listFilter);
        //音乐
        List<MusicBean> listMusic = new ArrayList<>();
        String[] name = getResources().getStringArray(R.array.music_name);
        listMusic.add(new MusicBean(R.raw.music1, name[0], R.drawable.ayy1, false));
        listMusic.add(new MusicBean(R.raw.music2, name[1], R.drawable.ayy2, false));
        listMusic.add(new MusicBean(R.raw.music3, name[2], R.drawable.ayy3, false));
        listMusic.add(new MusicBean(R.raw.music4, name[3], R.drawable.ayy4, false));
        listMusic.add(new MusicBean(R.raw.music5, name[4], R.drawable.ayy5, false));
        musicAdapter.setList(listMusic);
        //贴纸
        List<MyStickerBean> listSticker = new ArrayList<>();
        listSticker.add(new MyStickerBean(R.drawable.iv_tz1, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz2, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz3, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz4, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz5, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz6, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz7, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz8, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz9, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz10, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz11, false));
        listSticker.add(new MyStickerBean(R.drawable.iv_tz12, false));
        stickerAdapter.setList(listSticker);
        setSticker();
        //文字
        List<MyColorBean> listColor = new ArrayList<>();
        listColor.add(new MyColorBean("#000000", true));
        listColor.add(new MyColorBean("#FFFFFF", false));
        listColor.add(new MyColorBean("#E12D2D", false));
        listColor.add(new MyColorBean("#FFA8A8", false));
        listColor.add(new MyColorBean("#FFB652", false));
        listColor.add(new MyColorBean("#FFF62C", false));
        listColor.add(new MyColorBean("#79BA56", false));
        listColor.add(new MyColorBean("#35B9B0", false));
        listColor.add(new MyColorBean("#3F68BC", false));
        listColor.add(new MyColorBean("#9F45F1", false));
        listColor.add(new MyColorBean("#E85C90", false));
        listColor.add(new MyColorBean("#C0C0C0", false));
        listColor.add(new MyColorBean("#CA58C9", false));
        listColor.add(new MyColorBean("#8A72E1", false));
        listColor.add(new MyColorBean("#46D5AF", false));
        listColor.add(new MyColorBean("#5E8C4F", false));
        colorAdapter.setList(listColor);
        mDataBinding.txtStickerView.setTextColor(Color.parseColor("#000000"));
        //保存弹框
        saveDialog();
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.azantinzhong2);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    //保存视频
    private void saveVideo() {
        seekBar.setVisibility(View.VISIBLE);
        llVideoSaveSuc.setVisibility(View.GONE);
        textView.setText(getString(R.string.video_save_ing));
        mySaveDialog.show();
        seekBar.setProgress(new Random().nextInt(60));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, savePath);
                        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + FileUtils.getFileName(savePath);
                        FileUtils.copy(savePath, path);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        textView.setText(getString(R.string.video_save_suc));
                        seekBar.setVisibility(View.GONE);
                        llVideoSaveSuc.setVisibility(View.VISIBLE);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        }, 1000);
                    }
                });
            }
        }, 1000);
    }

    //剪切视频
    private void cutVideo() {
        if (tailorEndTime == 0 && tailorStartTime == 0) {
            ToastUtils.showShort(R.string.cut_tip);
        } else {
            mDataBinding.ivVideoEditSave.setEnabled(false);
            EditorHolder.editor().videoCut(videoPath, tailorStartTime, tailorEndTime, new IEditorListener() {
                @Override
                public void onSuccess(String outFilePath) {
                    dismissDialog();
                    videoPath = outFilePath;
                    String resultFile = FileUtil.generateFilePath(Content.Temp, ".mp4");
                    FileUtils.copy(outFilePath, resultFile);
                    mDataBinding.ivVideoEditSave.setEnabled(true);
                    ToastUtils.showShort(R.string.cut_suc);
                }

                @Override
                public void onFailure(String errMsg) {
                    dismissDialog();
                    mDataBinding.ivVideoEditSave.setEnabled(true);
                    ToastUtils.showShort(R.string.cut_def);
                }

                @Override
                public void onProgress(int progress) {
                    showDialog(getString(R.string.corp_ing) + progress + "%");
                }
            });
        }
    }

    //添加滤镜
    private void filterVideo() {
        EpVideo epVideo = new EpVideo(videoPath);
        epVideo.addFilter(filter);
        String path = FileUtil.generateFilePath(Content.Temp, ".mp4", videoPath);
        EpEditor.OutputOption outputOption = new EpEditor.OutputOption(path);
        EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        isFilter = false;
                        videoPath = path;
                        //设置播放器
                        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                        mDataBinding.videoView.setVideoPath(videoPath);
                        mDataBinding.videoView.seekTo(1);
                        mDataBinding.videoView.start();
                        startTime();
                    }
                });
            }

            @Override
            public void onFailure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        isFilter = false;
                        ToastUtils.showShort(R.string.add_filter_def);
                    }
                });
            }

            @Override
            public void onProgress(float progress) {
                float v = progress * 100;
                if (v < 0) {
                    v = 0;
                } else if (v > 100) {
                    v = 100;
                }
                showDialog(getString(R.string.add_filter_ing) + new DecimalFormat("#.0").format(v) + "%");
            }
        });
    }

    //变速
    private void videoSpeed() {
        EditorHolder.editor().videoChangeSpeed(videoPath, mCurSpeed, SpeedMode.ALL, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.speed_suc));
                savePath = outFilePath;
                videoPath = savePath;
                mDataBinding.videoView.setVideoPath(savePath);
                mDataBinding.videoView.seekTo(1);
                mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                mDataBinding.videoView.start();
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.speed_def));
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.speed_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }

    //贴纸
    private void videoSticker() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String imagePath;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.ivStickerView);
                imagePath = FileUtil.generateFilePath(Content.Temp, ".png");
                boolean save = ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean isSave) {
                if (isSave) {
                    EpDraw epDraw = new EpDraw(imagePath, 0, 0, videoWidth, videoHeight, false);
                    epDraw.setRotate(0);
                    String resultFile = FileUtil.generateFilePath(Content.Temp, ".mp4");//保存到我的视频
                    EpVideo epVideo = new EpVideo(videoPath);
                    epVideo.addDraw(epDraw);
                    EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                    EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    mDataBinding.ivStickerView.clear();
                                    ToastUtils.showShort(R.string.sticker_suc);
                                    savePath = resultFile;
                                    videoPath = savePath;
                                    //设置播放器
                                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                                    mDataBinding.videoView.setVideoPath(savePath);
                                    mDataBinding.videoView.seekTo(1);
                                    mDataBinding.videoView.start();
                                }
                            });
                        }

                        @Override
                        public void onFailure() {
                            dismissDialog();
                            ToastUtils.showShort(R.string.sticker_def);
                        }

                        @Override
                        public void onProgress(float progress) {
                            float v = progress * 100;
                            if (v < 0) {
                                v = 0;
                            } else if (v > 100) {
                                v = 100;
                            }
                            showDialog(getString(R.string.sticker_ing)
                                    + new DecimalFormat("#.0").format(v) + "%");
                        }
                    });
                }
            }
        });
    }

    //文字
    private void videoText() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String imagePath;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.txtStickerView);
                imagePath = FileUtil.generateFilePath(Content.Temp, ".png");
                boolean save = ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean isSave) {
                if (isSave) {
                    EpDraw epDraw = new EpDraw(imagePath, 0, 0, videoWidth, videoHeight, false);
                    epDraw.setRotate(0);
                    String resultFile = FileUtil.generateFilePath(Content.Temp, ".mp4");//保存到我的视频
                    EpVideo epVideo = new EpVideo(videoPath);
                    epVideo.addDraw(epDraw);
                    EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                    EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    mDataBinding.txtStickerView.clearTextContent();
                                    ToastUtils.showShort(R.string.text_suc);
                                    savePath = resultFile;
                                    videoPath = savePath;
                                    //设置播放器
                                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                                    mDataBinding.videoView.setVideoPath(savePath);
                                    mDataBinding.videoView.seekTo(1);
                                    mDataBinding.videoView.start();
                                }
                            });
                        }

                        @Override
                        public void onFailure() {
                            dismissDialog();
                            ToastUtils.showShort(R.string.text_def);
                        }

                        @Override
                        public void onProgress(float progress) {
                            float v = progress * 100;
                            if (v < 0) {
                                v = 0;
                            } else if (v > 100) {
                                v = 100;
                            }
                            showDialog(getString(R.string.text_ing)
                                    + new DecimalFormat("#.0").format(v) + "%");
                        }
                    });
                }
            }
        });
    }

    //设置贴纸
    private void setSticker() {
        // 获取videoView真实的宽高大小
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoWidth = mp.getVideoWidth();
                videoHeight = mp.getVideoHeight();
            }
        });
        // 将stickerView的宽高大小设置成videoView一样的大小
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                StkRelativeLayout.LayoutParams stickerLayoutParams = (StkRelativeLayout.LayoutParams) mDataBinding.ivStickerView.getLayoutParams();
                stickerLayoutParams.width = right - left;
                stickerLayoutParams.height = bottom - top;
                mDataBinding.ivStickerView.setLayoutParams(stickerLayoutParams);
                RelativeLayout.LayoutParams stickerLayoutParams1 = (RelativeLayout.LayoutParams) mDataBinding.txtStickerView.getLayoutParams();
                stickerLayoutParams1.width = right - left;
                stickerLayoutParams1.height = bottom - top;
                mDataBinding.txtStickerView.setLayoutParams(stickerLayoutParams1);
            }
        });
    }

    private String saveToSDCard(int music) {
        try {
            InputStream inStream = getResources().openRawResource(music);
            String path = FileUtil.generateFilePath(Content.Temp, ".mp4");
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            byte[] buffer = new byte[10];
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] bs = outStream.toByteArray();
            fileOutputStream.write(bs);
            outStream.close();
            inStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtils.delete(PathUtils.getFilesPathExternalFirst() + Content.Temp);
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    private void clearSelection() {
        mDataBinding.llSpeed1.setBackgroundColor(Color.parseColor("#F1F1F1"));
        mDataBinding.tvSpeed1.setTextColor(Color.parseColor("#000000"));
        mDataBinding.llSpeed2.setBackgroundColor(Color.parseColor("#F1F1F1"));
        mDataBinding.tvSpeed2.setTextColor(Color.parseColor("#000000"));
        mDataBinding.llSpeed3.setBackgroundColor(Color.parseColor("#F1F1F1"));
        mDataBinding.tvSpeed3.setTextColor(Color.parseColor("#000000"));
        mDataBinding.llSpeed4.setBackgroundColor(Color.parseColor("#F1F1F1"));
        mDataBinding.tvSpeed4.setTextColor(Color.parseColor("#000000"));
    }

    //保存弹框
    private void saveDialog() {
        mySaveDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_video_save, null);
        mySaveDialog.setContentView(inflate);
        mySaveDialog.setCancelable(true);
        Window dialogWindow = mySaveDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvGoRecord);
        seekBar = inflate.findViewById(R.id.sbProgress);
        textView = inflate.findViewById(R.id.tvVideoSaveTitle);
        llVideoSaveSuc = inflate.findViewById(R.id.llVideoSaveSuc);
        right.setOnClickListener(this);
    }


    @Override
    public void clipLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {
        tailorStartTime = cutStartTime;
        tailorEndTime = cutEndTime;
    }

    @Override
    public void clipRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {
        tailorStartTime = cutStartTime;
        tailorEndTime = cutEndTime;
    }

    @Override
    public void cropFirstLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropFirstRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropSecondLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropSecondRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void splitFirstSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void splitSecondSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }
}